<?php

namespace App\Http\Controllers\Admin;

use Hash;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\ApiController;
use App\Models\Manager;
use Response;

class AuthenticateController extends ApiController
{

    /**
     * 登录授权
     */
    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|string|email|max:255',
            'password' => 'required',
        ]);

        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }

        // 判断用户是否存在
        $manager = Manager::where('email', $request['email'])->first();
        if(!$manager){
            return $this->failed("用户不存在！", 40001);
        }

        if(!Hash::check($request['password'], $manager->password)){ 
            return $this->failed('密码错误！', 40001);
        }else {
            $token = $manager->createToken($manager->id, ['admin'])->accessToken;
            return $this->success(compact('token'));
        }
    }


    /**
     * 退出登录
     */
    public function logout()
    {
        if (Auth::guard('manager')->check()){

            Auth::guard('manager')->user()->token()->revoke();

        }

        return $this->message('退出登录成功');
    }


    /**
     * Register api
     *
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|string|email|max:255|unique:projects',
            'password' => 'required',
            'c_password' => 'required|same:password',
        ]);

        if ($validator->fails()) {
            return result(500, $validator->errors()->first());
        }

        $input = $request->all();
        $input['password'] = bcrypt($input['password']);
        $user = Project::create($input);
        $token =  $user->createToken('manager')->accessToken;

        return result(200, '授权成功', ['token'=>$token]);
    }

    /**
     * profile api
     *
     * @return \Illuminate\Http\Response
     */
    public function profile()
    {
        $manager = Auth::guard('manager')->user();

        $data = array(
            'roles' => $manager->id === 1 ? ['admin'] : ['store'],
            'avatar' => '',
            'name' => $manager->email,
            'introduction' => $manager->email
        );

        return $this->success($data);
    }

}
